<template>
  <div :id="charts.chart.id" style="min-width: 1000px; min-height: 300px"/>
</template>

<script>
import lodash from 'lodash'
import charts from '@/components/Charts/mixin/charts'

export default {
  mixins: [charts],
  data() {
    return {
      charts: {
        chart: {
          id: lodash.uniqueId('chart_'), // 保证全局唯一的 id，避免一个页面多个图表时 id 冲突
          instance: null, // charts mixin 时会通过混入的方式初始化 echarts 实例到这个属性
          timer: null,
          // 这种函数写法 this 作用域为： charts.chart
          bind() { // 用于绑定图表事件: instance 初始化完成之后 mixin 触发
            this.updateOption()
            this.timer = setInterval(this.updateOption, 3000)
          },
          // 这种函数写法 this 作用域为： charts.chart
          unbind() { // 用于解绑图表事件: instance 销毁之前 mixin 触发
            clearInterval(this.timer)
          },
          // 注意这里的函数定义写法同上面两个方法的区别，这里的 this 作用域为组件，因为这个方式是 setInterval 触发的，必须用这种形式定义
          updateOption: () => {
            this.charts.chart.instance.setOption({
              dataset: {
                source: [
                  ['product', '2012', '2013', '2014', '2015', '2016', '2017'],
                  ['Latte', ...(lodash.range(6).map(() => lodash.random(5, 95)))],
                  ['Milk', ...(lodash.range(6).map(() => lodash.random(5, 95)))],
                  ['Cheese', ...(lodash.range(6).map(() => lodash.random(5, 95)))],
                  ['Walnut', ...(lodash.range(6).map(() => lodash.random(5, 95)))]
                ]
              }
            })
          },
          option: {
            legend: {},
            tooltip: {},
            dataset: {source: []},
            series: [
              {type: 'pie', radius: 50, center: ['15%', '50%']/* No encode specified, by default, it is '2012'.*/},
              {type: 'pie', radius: 50, center: ['35%', '50%'], encode: {itemName: 'product', value: '2013'}},
              {type: 'pie', radius: 50, center: ['60%', '50%'], encode: {itemName: 'product', value: '2014'}},
              {type: 'pie', radius: 50, center: ['85%', '50%'], encode: {itemName: 'product', value: '2015'}}
            ]
          }
        }
      }
    }
  }
}
</script>
